#include "sc8.h"

#include "iot_uart.h"

#include <string.h>

/* 串口号 */
#define SC8_UART_ID EUART2_M1
/* sc8 数据长度 */
#define SC8_DATA_LENGTH 16

/**
 * @brief 获取 sc8 校验和
 *
 * @param ptr 数据
 * @return uint16_t
 */
static uint16_t sc8_check_sum(uint8_t *ptr)
{
    uint16_t check_sum = 0;

    for (uint8_t i = 0; i < 15; i++)
    {
        check_sum += *ptr;
        ptr++;
    }

    return (check_sum & 0xFF);
}

/**
 * @brief sc8 初始化
 *
 */
void sc8_init(void)
{
    IotUartAttribute attr;

    attr.baudRate = 9600;
    attr.dataBits = IOT_UART_DATA_BIT_8;
    attr.pad = IOT_FLOW_CTRL_NONE;
    attr.parity = IOT_UART_PARITY_NONE;
    attr.rxBlock = IOT_UART_BLOCK_STATE_NONE_BLOCK;
    attr.stopBits = IOT_UART_STOP_BIT_1;
    attr.txBlock = IOT_UART_BLOCK_STATE_NONE_BLOCK;

    IoTUartInit(SC8_UART_ID, &attr);
}

/**
 * @brief 获取 sc8 数据
 *
 * @return uint16_t
 */
uint16_t sc8_get(void)
{
    int8_t ret = 0;
    uint8_t buf[SC8_DATA_LENGTH] = {0};
    uint8_t packet_hand[] = {0x42, 0x4D, 0x00};
    static uint16_t last_data = 0;

    ret = IoTUartRead(SC8_UART_ID, buf, SC8_DATA_LENGTH);
    if (ret < 0)
    {
        printf("read uart fail, ret is %d\r\n", ret);
        return last_data;
    }

    uint8_t *ptr = strstr(buf, packet_hand);

    if (ptr[15] == sc8_check_sum(ptr))
    {
        uint16_t ppm = ptr[6] * 256 + ptr[7];
        last_data = ppm;
        return ppm;
    }
    else
    {
        return last_data;
    }
}
